import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, ScrollView, Dimensions
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import MethodUtil from '../../../utils/MethodUtil';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { ApprovalView, RefuseModal } from '../../../component/ModalVerifylComponent.js';
import { LightBox } from '../../../component/Store';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { ModifyBaseInfo } from './_components/ModifyBaseInfo';
import { BaseItem } from './_components/BaseItem';
import { CommonChangeInfo } from './_components/CommonChangeInfo';
import { AnnexInfo } from './_components/AnnexInfo';
import { ProductInfo } from './_components/ProductInfo';
import { ProgressModal } from '../../../components/common/ProgressModal';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
import ModalPicsComponent from '../../customer-management/enterprise/details/_components/ModalPicsComponent';

const leftArrows = require('../../../imgs/credit/leftArrows.png');//闭口图标
const change = require('../../../imgs/credit/change.png');//闭口图标
const scale = GLOBAL.SCALE;
const modalPicDelCfg = {
	visible: false,
	urls: [],
	picPress: () => { },
}

export class ChangeDetailPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const params = navigation.state.params || {};
		return {
			headerTitle: params.title || '变更合同详情',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('ApproveListPage', { choice: params.choice || {} }) }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	requesting;
	constructor(props) {
		super(props);
		const { paramsData, status, choice } = props.navigation.state.params;
		const { changeId, taskId, formKey, approveType } = paramsData || {};
		this.changeId = changeId || '';
		this.taskId = taskId || '';
		this.formKey = formKey || '';
		this.status = status;
		this.choice = choice || {};
		this.approveType = approveType;
		this.state = {
			data: {},
			resultModalVisible: false,
			loaded: false,
			lightBoxVisible: false,
			stateLightBoxData: false,
			stepData: [],
			previewModalVisible: false,
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '',
				rowDataList: [],
			},
			showRight: false
		};
	}

	async componentWillMount() {
		await this._getDetailData();
		await this._findNode();
	}

	//初始化详情数据
	async _getDetailData() {
		this.setState({
			loaded: true
		});
		let url = this.approveType == "LC" ? API.ORDER_LONG_APPROVE_DETAILS : API.ORDER_CHANGE_DETAIL;
		let responseData = await HTTP.GET(API_GENERATE(url), {
			changeId: this.changeId,
			formKey: this.formKey,
			corpId: this.choice.corpId
		});
		console.log("responseData-变更数据", responseData)
		this.setState({ loaded: false });
		if (responseData && responseData.success && responseData.data) {
			this.setState({
				data: responseData.data,
				showRight: responseData.data.changesInfo.isNeedFwAudit ? true : false
			})
		}
	}

	//审批流查询
	_findNode = async () => {
		let stepData = [];
		let { data } = this.state;
		let { changesInfo } = data || {};
		let { changeId, processInstanceId, corpId } = changesInfo || {};
		let findNodeData = await HTTP.GET(API_GENERATE(API.ORDER_APPROVE_LOG), {
			processInstanceId,
			bizId: changeId,
			// bizObjType: '16',
			corpId,
		});

		findNodeData = findNodeData && findNodeData.map((item) => {
			if (item.auditResult == 9) {
				item.auditResultName = '操作';
			}
			return item;
		})

		console.log('findNodeData', findNodeData);
		let { lightBoxData } = this.state;
		lightBoxData.title = '审批状态';
		lightBoxData.rowDataList = findNodeData;
		this.setState({
			lightBoxData
		})
	}

	_showApproveLog() {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		this.setState({
			lightBoxData
		})
	}

	//审批流弹框
	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	//同意，驳回接口调用
	getApprovalView() {
		//HASLOT 已审批   LOT未审批
		return (this.status && this.status === 'LOT') ? (
			<View style={{ backgroundColor: '#fff' }}>
				<ApprovalView agreePress={() => {
					this.isAgreed = '1';
					this.remark = '';
					this.setState({
						refuseModalVisible: true
					})

				}} refusePress={() => {
					this.isAgreed = '0';
					this.remark = '';
					this.setState({
						refuseModalVisible: true
					})
				}}
					agreeSignPress={() => {
						this.isAgreed = '1';
						this.remark = '';
						this.setState({
							showSignRejectModal: true
						})

					}}
					showRight={this.state.showRight}
				/>
			</View>
		) : null;
	}

	async _fetchApproval() {
		let { data } = this.state;
		let { changesInfo } = data || {};
		let { changeId, processInstanceId, formKey } = changesInfo || {};
		if (this.requesting) return;
		this.setState({
			refuseModalVisible: false,
			loaded: true
		});

		let sendData = {};
		let url = {};
		if (this.approveType === "ZXYC") {//新油 - 变更
			sendData = {
				auditResult: this.isAgreed,
				businessKey: changeId,
				formKey: this.formKey,
				remark: this.remark,
				taskId: this.taskId
			}
			url = API.GET_NEW_OIL_ORDER_CHANGE_APPROVAL;
		} else if (this.approveType === "LC") { // 长约框架变更
			sendData = {
				auditResult: this.isAgreed,
				businessKey: changeId,
				formKey: this.formKey,
				remark: this.remark,
				taskId: this.taskId
			}
			url = API.LONG_ORDER_LIST_CHANGE;
		} else { // 订单变更
			sendData = {
				changeId,
				processInstanceId,
				auditResultName: this.isAgreed == '1' ? 'PASS' : 'UNPASS',
				remark: this.remark, // 填写
				corpId: this.choice.corpId,
				taskId: this.taskId
			}
			url = API.ORDER_CHANGE_APPROVAL;
		}



		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(url), sendData);

		this.setState({
			loaded: false
		});

		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => { this.props.navigation.goBack(); })
		} else {
			this.requesting = false;
		}
	}


	// 审批
	async _signApprove() {
		let { data } = this.state;
		let { changesInfo } = data || {};
		let { changeId, processInstanceId } = changesInfo || {};
		if (this.requesting) return;
		this.setState({
			showSignRejectModal: false,
			loaded: true
		});
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.ORDER_CHANGE_APPROVAL), {
			changeId,
			processInstanceId,
			auditResultName: 'PASS',
			corpId: this.choice.corpId,
			taskId: this.taskId,
			formKey: this.formKey,
			fwauditStatus: '1'
		});

		this.setState({
			loaded: false
		});

		if (responseData) {
			ToastUtil.showSuccess('审批成功').then(() => { this.props.navigation.goBack(); })
		} else {
			this.requesting = false;
		}
	}

	//查看合同
	_previeContract(id) {
		this.props.navigation.navigate('ContractPdfPage', { finalFileId: id })
	}
	//查看附件
	_previeAnnex(data) {
		const { fileExtName, fileId } = data;
		if (fileExtName && fileExtName.toLowerCase() == 'pdf') {
			this.props.navigation.navigate('ContractPdfPage', { finalFileId: fileId })
		} else {
			this._getImgPreview(fileId)
		}
	}
	//附件预览
	async _getImgPreview(fileId) {
		const response = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId });
		if (response && response.image && response.image.length) {
			modalPicDelCfg.visible = true;
			modalPicDelCfg.urls[0] = {
				url: response.image,
				width: Dimensions.get('window').width
			};
			modalPicDelCfg.picPress = () => {
				modalPicDelCfg.visible = false;
				modalPicDelCfg.urls = [];
				this.setState({
					previewModalVisible: false,
				});
			}
			this.setState({ ls: true });
		}
	}

	render() {
		let { paramsData } = this.props.navigation.state.params || {};
		let { approveType } = paramsData || {};
		let { lightBoxData, data } = this.state;
		let { rowDataList } = lightBoxData;
		let { goodsChangesInfo, changesInfo, goodsIds } = data;
		let { changeReason, remarkTypeName, orderId, oppoOrderId, bizMode, orderChangesTypeList, attachmentFileList, currencyName } = changesInfo || {};
		const approvalView = this.getApprovalView();
		currencyName = currencyName || '元';
		return (
			<View style={styles.container}>
				<View style={[styles.emptyBg, { flexDirection: 'row' }]}>
					<View style={styles.approveView}>
						<Text style={styles.approveViewLabel}>审批记录</Text>
					</View>
					<View style={styles.approveView}>
						<View style={styles.approveViewCenter}>
							<View style={styles.statusCircle}></View>
							<View style={styles.statusLine}></View>
						</View>
						<View style={styles.approveViewCenter}>
							{
								rowDataList && rowDataList.length ?
									<Text style={styles.statusRole}>{rowDataList.length > 1 ? `${rowDataList[1].taskName}.${rowDataList[1].auditStaffName}` : `${rowDataList[0].taskName}.${rowDataList[0].auditStaffName}`}</Text>
									: <Text style={styles.statusRole}>暂无审批记录</Text>
							}
							{
								rowDataList && rowDataList.length > 1 ?
									<Text style={styles.statusTime}>{`${rowDataList[1].auditTime || '-'} ${rowDataList[1].auditResultName || '-'}`}</Text>
									: null
							}
						</View>
					</View>
					<TouchableOpacity style={[styles.approveView, { flex: 1, justifyContent: 'center' }]} onPress={() => { this._showApproveLog() }}>
						<View style={{ marginTop: 10 * scale }}>
							<Image source={leftArrows}></Image>
						</View>
					</TouchableOpacity>
				</View>

				<ScrollView>
					<View style={styles.changeInfoView}>
						{
							changesInfo ?
								<View style={styles.changeInfoCard}>
									<View style={styles.changeInfoTitleView}>
										<Text style={styles.changeInfoTitle}>基本信息</Text>
									</View>
									<ModifyBaseInfo data={changesInfo} choice={this.choice} approveType={approveType} />
								</View> : null
						}
						<View style={styles.changeInfoCard}>
							<View style={styles.changeInfoTitleView}>
								<Text style={styles.changeInfoTitle}>变更说明</Text>
							</View>
							<BaseItem label={'变更原因类型'} afterValueDesc={remarkTypeName || '-'} />
							<BaseItem label={'变更原因'} afterValueDesc={changeReason || '-'} />
						</View>
						{
							goodsChangesInfo ?
								<View style={styles.changeInfoCard}>
									<View style={styles.changeInfoTitleView}>
										<Text style={styles.changeInfoTitle}>商品信息</Text>
										<Text style={styles.changeInfoSubtitle}>{bizMode ? `（闭口/${orderId}/${oppoOrderId}）` : ''}</Text>
									</View>
									<ProductInfo approveType={this.approveType} data={data} />
								</View> : null
						}
						{
							orderChangesTypeList && orderChangesTypeList.length ? orderChangesTypeList.map((item, index) => {
								const { changeType, changeTypeName, orderChangeLineList } = item || {};
								return (
									<View key={index} style={styles.changeInfoCard}>
										<View style={styles.changeInfoTitleView}>
											<Text style={styles.changeInfoTitle}>{changeTypeName}</Text>
											{changeType == '闭口' ? <Text style={styles.changeInfoSubtitle}>{`（闭口/${orderId}/${oppoOrderid}）`}</Text> : null}
										</View>
										<CommonChangeInfo currencyName={currencyName} data={orderChangeLineList} changeType={changeType}
											afterValueOnPress={(value) => this._previeContract(value)}
											beforeValueOnPress={(value) => this._previeContract(value)} />
									</View>
								)
							})
								: null
						}
						{
							attachmentFileList ?
								<View style={styles.changeInfoCard}>
									<View style={styles.changeInfoTitleView}>
										<Text style={styles.changeInfoTitle}>附件</Text>
									</View>
									<AnnexInfo data={attachmentFileList} onPress={(data) => this._previeAnnex(data)} />
								</View>
								: null
						}
					</View>
					<ModalPicsComponent {...modalPicDelCfg} />
				</ScrollView>
				{/* 审批流 */}
				<ProgressModal {...lightBoxData} />

				{approvalView}
				<RefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed == '1' ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed == '1' ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._fetchApproval();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}}
					signVisible={this.state.showSignRejectModal}
					btnSignPress={() => {
						this._signApprove();
					}}
					bgSignPress={() => {
						this.setState({
							showSignRejectModal: false,
						});
					}}
				/>

				{
					this.state.loaded ?
						<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
							<PageStatusIndex status='loading' />
						</View>
						: null
				}
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
		height: '100%'
	},
	emptyBg: {
		width: '100%',
		height: 69 * scale,
		backgroundColor: style.color.themeColor,
	},
	approveView: {
		flexDirection: 'row',
		alignItems: 'center',
	},
	approveViewLabel: {
		color: '#fff',
		fontSize: 12 * scale,
		marginTop: -20 * scale,
		paddingLeft: 22 * scale,
		paddingRight: 18 * scale
	},
	approveViewCenter: {
		marginRight: 12 * scale
	},
	statusCircle: {
		width: 9 * scale,
		height: 9 * scale,
		borderRadius: 6 * scale,
		backgroundColor: '#fff',
		opacity: 0.9
	},
	statusLine: {
		width: 1 * scale,
		height: 14 * scale,
		backgroundColor: '#fff',
		marginLeft: 4 * scale,
		opacity: 0.8
	},
	statusRole: {
		color: '#fff',
		fontSize: 12 * scale,
		marginBottom: 8 * scale
	},
	statusTime: {
		color: '#fff',
		fontSize: 10 * scale
	},
	changeInfoView: {
		backgroundColor: style.color.bgGray
	},
	changeInfoCard: {
		padding: 16 * scale,
		marginBottom: 12 * scale,
		backgroundColor: '#fff'
	},
	changeInfoTitleView: {
		flexDirection: 'row'
	},
	changeInfoTitle: {
		color: style.color.themeColor,
		fontSize: 14 * scale
	},
	changeInfoSubtitle: {
		color: '#999',
		fontSize: 12 * scale,
		marginLeft: 8 * scale
	}
})